<?php

//flush_rewrite_rules();

include get_template_directory() . "/templates/helpers.php";
include get_template_directory() . "/templates/listings_template.php";
include get_template_directory() . "/templates/wp_new_user_notification.php";
include get_template_directory() . "/templates/users_template.php";
include get_template_directory() . "/templates/settings_template.php";
include get_template_directory() . "/templates/providers_template.php";
include get_template_directory() . "/templates/bpa_template.php";
include get_template_directory() . "/templates/slides_template.php";
include get_template_directory() . "/endpoints/forgot_password.php";
include get_template_directory() . "/endpoints/subrubro.php";
include get_template_directory() . "/endpoints/register_user.php";
include get_template_directory() . "/endpoints/update_user_data.php";
include get_template_directory() . "/endpoints/register_year.php";
include get_template_directory() . "/endpoints/request_user_data.php";
include get_template_directory() . "/endpoints/request_list.php";
include get_template_directory() . "/endpoints/generate_data.php";
include get_template_directory() . "/endpoints/request_saving_data.php";

//
//flush_rewrite_rules();
//

class ecopyme_functions {

    public function __construct() {

        add_action('init', array(&$this, 'create_custom_taxonomies'));
        add_action('init', array(&$this, 'create_custom_post_type'));
        add_action('init', array(&$this, 'add_custom_roles'));
        add_action('init', array(&$this, 'add_custom_menues'));

        add_theme_support('post-thumbnails', array('slide', 'bpa'));
        add_theme_support('custom-header');
        
        //enqeue css
        add_action('wp_enqueue_scripts', array(&$this, 'theme_name_scripts'));
        add_action('after_setup_theme', array(&$this, 'login_check'));
        
        //Shortcode for home
        add_shortcode('check_login', array(&$this, 'check_login_handler'));
        
        add_filter('next_posts_link_attributes', array(&$this, 'add_class'));
        add_filter('previous_posts_link_attributes', array(&$this, 'add_class'));
        add_filter('show_admin_bar', '__return_false');
        
        add_action('admin_menu', array(&$this, 'add_users_import_page'));
        
        //Add User Fields
        add_action('user_new_form', array(&$this, 'add_extra_user_fields'));
        add_action('show_user_profile', array(&$this, 'add_extra_user_fields'));
        add_action('edit_user_profile', array(&$this, 'add_extra_user_fields'));
        
        //Save User Fields
        add_action('user_register', array(&$this, 'save_extra_user_fields'));
        add_action('personal_options_update', array(&$this, 'save_extra_user_fields'));
        add_action('edit_user_profile_update', array(&$this, 'save_extra_user_fields'));

        //BPA Metabox
        add_action('add_meta_boxes', array(&$this, 'bpa_metodology_metabox'));
        add_action('add_meta_boxes', array(&$this, 'bpa_amount_metabox'));
        add_action('add_meta_boxes', array(&$this, 'bpa_returns_metabox'));
        add_action('add_meta_boxes', array(&$this, 'bpa_providers_metabox'));
        add_action('add_meta_boxes', array(&$this, 'bpa_water_metabox'));
        add_action('add_meta_boxes', array(&$this, 'bpa_energy_metabox'));
        add_action('save_post', array(&$this, 'bpa_save_metabox'));
        add_action('admin_print_styles', array(&$this, 'bpa_admin_styles'));
        add_action('admin_enqueue_scripts', array(&$this, 'bpa_admin_js'));

        //Proveedor Metabox
        add_action('add_meta_boxes', array(&$this, 'provider_metabox'));
        add_action('save_post', array(&$this, 'provider_save_metabox'));
        add_action('admin_print_styles', array(&$this, 'provider_admin_styles'));
        add_action('admin_enqueue_scripts', array(&$this, 'provider_admin_js'));
        
        //Slider Metabox
        add_action('add_meta_boxes', array(&$this, 'slider_metabox'));
        add_action('save_post', array(&$this, 'slider_save_metabox'));
        add_action('admin_print_styles', array(&$this, 'slider_admin_styles'));
        add_action('admin_enqueue_scripts', array(&$this, 'slider_admin_js'));
        
    }
    
    public function create_custom_taxonomies() {

        $args = array(
            'label'         => __('Tipo de consumo'),
            'rewrite'       => array('slug' => 'tipo-consumo'),
            'hierarchical'  => true,
            'has_archive'   => true
        );
        register_taxonomy('tipo-consumo', 'bpa', $args);
        
        $args = array(
            'label'         => __('Plazo'),
            'rewrite'       => array('slug' => 'plazo'),
            'hierarchical'  => true,
            'has_archive'   => true
        );
        register_taxonomy('plazo', 'bpa', $args);
        
        flush_rewrite_rules();
        
    }

    public function create_custom_post_type() {

        $labels = array(
            'name' => __('Buenas Practicas Ambientales'),
            'singular_name' => __('BPA'),
            'edit_item' => __('Editar BPA'),
            'update_item' => __('Actualizar BPA'),
            'add_new_item' => __('Agregar Nueva BPA'),
            'new_item_name' => __('Nuevo nombre de BPA'),
            'menu_name' => __('BPA'),
        );
        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => true,
            'capability_type' => 'post',
            'hierarchical' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail')
            /*'taxonomies' => array('post_tag'),*/
        );
        register_post_type('bpa', $args);

        //Proveedores
        $labels = array(
            'name' => __('Proveedores'),
            'singular_name' => __('Proveedor'),
            'edit_item' => __('Editar Proveedor'),
            'update_item' => __('Actualizar Proveedor'),
            'add_new_item' => __('Agregar Nuevo Proveedor'),
            'new_item_name' => __('Nuevo nombre de Proveedor'),
            'menu_name' => __('Proveedor'),
        );
        register_post_type('provider', array(
            'labels' => $labels,
            'public' => true,
            'has_archive' => true,
            'supports' => array('title',
                'thumbnail'
            ),
                )
        );

        //Slides
        $labels = array(
            'name' => __('Slides'),
            'singular_name' => __('Slide'),
            'edit_item' => __('Editar Slide'),
            'update_item' => __('Actualizar Slide'),
            'add_new_item' => __('Agregar Nuevo Slide'),
            'new_item_name' => __('Nuevo nombre de Slide'),
            'menu_name' => __('Slide'),
        );
        register_post_type('slide', array(
            'labels' => $labels,
            'public' => true,
            'has_archive' => false,
            'supports' => array('title',
                'editor',
            ),
                )
        );

        flush_rewrite_rules();
    }

    public function add_custom_roles() {
        
        add_role('content_manager', 'Editor de Contenido', array(
            'read' => true, // True allows that capability
            'edit_posts' => false,
            'delete_posts' => false,
        ));

        add_role('company', 'Empresa', array(
            'read' => true, // True allows that capability
            'edit_posts' => false,
            'delete_posts' => false,
        ));
        
    }
    
    public function add_custom_menues() {
        register_nav_menus(array(
            'footer_menu' => 'My Custom Footer Menu',
        ));
    }
    
    public function theme_name_scripts() {
        wp_enqueue_style('base-css', get_stylesheet_uri());
    }
    
    public function login_check() {
        if (isset($_POST) && isset($_POST['kind']) && $_POST['kind'] != "") {
            $creds = array();
            $creds['user_login'] = $_POST['username'];
            $creds['user_password'] = $_POST['password'];
            $creds['remember'] = true;
            $user = wp_signon($creds, false);

            if (is_wp_error($user)) {
                $error = $user->get_error_message();
                $msg = urlencode("RUC o contrase&ntilde;a inv&aacute;lidos");
                $redirect = Helpers::get_base_url() . $_SERVER["REQUEST_URI"] . "?err=" . $msg;
                wp_redirect($redirect);
                exit();
            } else {
                wp_redirect(Helpers::get_dashboard_url());
                exit();
            }
        }
    }
    
    function check_login_handler($atts) {
        $a = shortcode_atts(array(
            'logged_in' => '',
            'not_logged_in' => '',
                ), $atts);
        if (is_user_logged_in()) {
            return ' ' . $a['logged_in'] . ' ';
        } else {
            return ' ' . $a['not_logged_in'] . ' ';
        }
    }

    function add_class() {
        return 'class="buton"';
    }

    /* USERS IMPORT-EXPORT OPTION TEMPLATE */
    
    public function add_users_import_page() {
        //Import users option
        add_users_page('Importar Usuarios', 'Importar Usuarios', 'manage_options', 'import-users', array(&$this, 'import_users'));
        add_users_page('Exportar data de Usuarios', 'Exportar data de Usuarios', 'manage_options', 'export-data-users', array(&$this, 'export_data_users'));
        add_options_page('Gesti&oacute;n de Par&aacute;metros del Sistema', 'Gesti&oacute;n de Par&aacute;metros del Sistema', 'manage_options', 'configuracion-parametros', array(&$this, 'configure_water_price'));
    }

    public function import_users() {
        UsersTemplate::showImportUsersForm();
    }

    public function export_data_users() {
        UsersTemplate::showExportsUserForm();
    }

    public function configure_water_price() {
        SettingsTemplate::showPricePanel();
    }

    /* USERS ADMIN TEMPLATE */
    
    public function add_extra_user_fields($user) {
        UsersTemplate::getForm($user);
    }
    
    public function save_extra_user_fields($user) {
        UsersTemplate::saveForm($user);
    }
    
    /* BPA ADMIN TEMPLATE */
    
    public function bpa_metodology_metabox() {
        add_meta_box('bpa_metodology_metabox', 'Metodología', array($this, 'bpa_metodology_metabox_callback'), 'bpa');
    }

    public function bpa_amount_metabox() {
        add_meta_box('bpa_amount_metabox', 'Monto de inversión', array($this, 'bpa_amount_metabox_callback'), 'bpa');
    }

    public function bpa_returns_metabox() {
        add_meta_box('bpa_returns_metabox', 'Retorno en meses', array($this, 'bpa_returns_metabox_callback'), 'bpa');
    }
    
    public function bpa_providers_metabox() {
        add_meta_box('bpa_providers_metabox', 'Proveedores', array($this, 'bpa_providers_metabox_callback'), 'bpa');
    }

    public function bpa_savings_metabox() {
        add_meta_box('bpa_savings_metabox', 'Monto de ahorro', array($this, 'bpa_savings_metabox_callback'), 'bpa');
    }

    public function bpa_water_metabox() {
        add_meta_box('bpa_water_metabox', 'Agua - Monto de ahorro', array($this, 'bpa_water_metabox_callback'), 'bpa');
    }

    public function bpa_energy_metabox() {
        add_meta_box('bpa_energy_metabox', 'Energia - Monto de ahorro', array($this, 'bpa_energy_metabox_callback'), 'bpa');
    }
    
    public function bpa_metodology_metabox_callback($post) {
        BPATemplate::generateBPAMetodologyMetabox($post);
    }

    public function bpa_amount_metabox_callback($post) {
        BPATemplate::generateBPAAmountMetabox($post);
    }

    public function bpa_returns_metabox_callback($post) {
        BPATemplate::generateBPAReturnsMetabox($post);
    }
    
    public function bpa_providers_metabox_callback($post) {
        BPATemplate::generateBPAProvidersMetabox($post);
    }

    public function bpa_savings_metabox_callback($post) {
        BPATemplate::generateBPASavingsMetabox($post);
    }

    public function bpa_water_metabox_callback($post) {
        BPATemplate::generateBPAWaterMetabox($post);
    }

    public function bpa_energy_metabox_callback($post) {
        BPATemplate::generateBPAEnergyMetabox($post);
    }
    
    public function bpa_save_metabox($post_id) {
        BPATemplate::saveBPAMetabox($post_id);
    }
    
    function bpa_admin_styles() {
        global $typenow;
        if ($typenow == 'bpa') {
            wp_enqueue_style('bpa_meta_box_styles', get_template_directory_uri() . '/css/metabox.css');
        }
    }
    
    function bpa_admin_js() {
        global $typenow;
        if ($typenow == 'bpa') {
            wp_enqueue_script('bpa_script', get_template_directory_uri() . '/js/bpa_logic.js');
            wp_enqueue_script('mask_script', get_template_directory_uri() . '/js/jquery.mask.js');
        }
    }

    /* PROVIDER ADMIN TEMPLATE */
    
    public function provider_metabox() {
        add_meta_box('provider_metabox', 'Info de Proveedor', array($this, 'provider_metabox_callback'), 'provider');
    }
    
    public function provider_metabox_callback($post) {
        ProviderTemplate::generateProviderMetabox($post);
    }
    
    public function provider_save_metabox($post_id) {
        ProviderTemplate::saveProviderMetabox($post_id);
    }

    function provider_admin_styles() {
        if ($typenow == 'provider') {
            wp_enqueue_style('prfx_meta_box_styles', get_template_directory_uri() . '/css/meta-box-styles.css');
        }
    }
    
    function provider_admin_js() {
        global $typenow;
        if ($typenow == 'provider') {
            wp_enqueue_media();
        }
    }

    /* SLIDER ADMIN TEMPLATE */
    
    public function slider_metabox() {
        add_meta_box('slide_metabox', 'Info de Slides', array($this, 'slide_metabox_callback'), 'slide');
    }
    
    public function slide_metabox_callback($post) {
        SlidesTemplate::generateSlideMetabox($post);
    }
    
    public function slider_save_metabox($post_id) {
        SlidesTemplate::saveSlideMetabox($post_id);
    }
    
    function slider_admin_styles() {
        if ($typenow == 'slide') {
            wp_enqueue_style('prfx_meta_box_styles', get_template_directory_uri() . '/css/meta-box-styles.css');
        }
    }
    
    function slider_admin_js() {
        global $typenow;
        if ($typenow == 'slide') {
            wp_enqueue_media();

            // Registers and enqueues the required javascript.
            wp_register_script('meta-box-image', get_template_directory_uri() . '/js/metabox-image.js', array('jquery'));
            wp_localize_script('meta-box-image', 'meta_image', array(
                'title' => __('Choose or Upload an Image', 'prfx-textdomain'),
                'button' => __('Use this image', 'prfx-textdomain'),
                    )
            );
            wp_enqueue_script('meta-box-image');
        }
    }

}

Helpers::init();
$ecopyme_functions = new ecopyme_functions();

add_filter('wp_mail_from', 'new_mail_from');
add_filter('wp_mail_from_name', 'new_mail_from_name');

function new_mail_from($old) {
    return 'noreply@ecopyme.pe';
}

function new_mail_from_name($old) {
    return 'Ecopyme';
}

function update_workers_number($user_login, $user) {

    $user_id = $user->ID;
    $current_year = date('Y');
    $current_month = date('n');

    global $wpdb;

    $last_data_year = 2010;
    $last_data_month = 0;
    $last_data_number = 0;

    $last_data = $wpdb->get_row($wpdb->prepare("select year,month,number from bpa_registry_workers where user_id = %d order by year desc, month desc limit 1", $user_id));
    if ($last_data != null) {
        $last_data_year = $last_data->year;
        $last_data_month = $last_data->month;
        $last_data_number = $last_data->number;
    }

    for ($y = $last_data_year; $y <= $current_year; $y++) {
        $begin_month = $y == $last_data_year ? $last_data_month + 1 : 1;
        $end_month = $y < $current_year ? 12 : $current_month;
        for ($m = $begin_month; $m <= $end_month; $m++) {
            $wpdb->query($wpdb->prepare("insert into bpa_registry_workers (user_id, year, month, number) 
                values (%d, %d, %d, %d)", $user_id, $y, $m, $last_data_number));
        }
    }
}

function update_sector($user_login, $user) {

    $user_id = $user->ID;
    $current_year = date('Y');
    $current_month = date('n');

    global $wpdb;

    $last_data_year = 2010;
    $last_data_month = 0;
    $last_data_sector_id = 0;
    $last_data_subsector_id = 0;

    $last_data = $wpdb->get_row($wpdb->prepare("select sector_id,subsector_id,year,month from bpa_registry_sector where user_id = %d order by year desc, month desc limit 1", $user_id));
    if ($last_data != null) {
        $last_data_year = $last_data->year;
        $last_data_month = $last_data->month;
        $last_data_sector_id = $last_data->sector_id;
        $last_data_subsector_id = $last_data->subsector_id;
    } else {
        $first_sector = $wpdb->get_var("select id from bpa_company_sector order by id asc limit 1");
        $first_subsector = $wpdb->get_row($wpdb->prepare("select id from bpa_company_subsector where sector_id = %d order by id asc limit 1", $first_sector));
        $last_data_sector_id = $first_sector != null ? $first_sector : 0;
        $last_data_subsector_id = $first_subsector != null ? $first_subsector : 0;
    }

    for ($y = $last_data_year; $y <= $current_year; $y++) {
        $begin_month = $y == $last_data_year ? $last_data_month + 1 : 1;
        $end_month = $y < $current_year ? 12 : $current_month;
        for ($m = $begin_month; $m <= $end_month; $m++) {
            $wpdb->query($wpdb->prepare("insert into bpa_registry_sector (user_id, sector_id, subsector_id, year, month) 
                values (%d, %d, %d, %d, %d)", $user_id, $last_data_sector_id, $last_data_subsector_id, $y, $m));
        }
    }
}

function update_product($user_login, $user) {

    $user_id = $user->ID;
    $current_year = date('Y');
    $current_month = date('n');

    global $wpdb;

    $last_data_year = 2010;
    $last_data_month = 0;
    $last_data_product = '';

    $last_data = $wpdb->get_row($wpdb->prepare("select product,year,month from bpa_registry_product where user_id = %d order by year desc, month desc limit 1", $user_id));
    if ($last_data != null) {
        $last_data_year = $last_data->year;
        $last_data_month = $last_data->month;
        $last_data_product = $last_data->product;
    }

    for ($y = $last_data_year; $y <= $current_year; $y++) {
        $begin_month = $y == $last_data_year ? $last_data_month + 1 : 1;
        $end_month = $y < $current_year ? 12 : $current_month;
        for ($m = $begin_month; $m <= $end_month; $m++) {
            $wpdb->query($wpdb->prepare("insert into bpa_registry_product (user_id, product, year, month) 
                values (%d, %s, %d, %d)", $user_id, $last_data_product, $y, $m));
        }
    }
}

function update_consumption($user_login, $user) {

    $user_id = $user->ID;
    $current_year = date('Y');
    $current_month = date('n');

    global $wpdb;

    $types = $wpdb->get_results("select t.id as type_id, st.id as subtype_id from bpa_consumption_type t left join bpa_consumption_subtype st on t.id = st.type_id");

    foreach ($types as $type) {

        $type_id = $type->type_id;
        $subtype_id = $type->subtype_id == null ? 0 : $type->subtype_id;

        $last_data_year = 2010;
        $last_data_month = 0;

        $last_data = $wpdb->get_row($wpdb->prepare("select * from bpa_registry_consumption where user_id = %d and type_id = %d and subtype_id = %d order by year desc, month desc limit 1", $user_id, $type_id, $subtype_id));
        if ($last_data != null) {
            $last_data_year = $last_data->year;
            $last_data_month = $last_data->month;
        }

        for ($y = $last_data_year; $y <= $current_year; $y++) {
            $begin_month = $y == $last_data_year ? $last_data_month + 1 : 1;
            $end_month = $y < $current_year ? 12 : $current_month;
            for ($m = $begin_month; $m <= $end_month; $m++) {
                $wpdb->query($wpdb->prepare(
                                "insert into bpa_registry_consumption (user_id, type_id, subtype_id, year, month, quantity, price) 
                values (%d, %d, %d, %d, %d, %d, %d)", $user_id, $type_id, $subtype_id, $y, $m, 0, 0));
            }
        }
    }
}

function update_inventory($user_login, $user) {

    $user_id = $user->ID;

    global $wpdb;

    $inventory_number = $wpdb->get_var($wpdb->prepare("select count(*) from bpa_inventory_user where user_id = %d", $user_id));

    if ($inventory_number == 0) {
        $wpdb->query($wpdb->prepare("insert into bpa_inventory_user(user_id, item_id, quantity)
                select %d, id, 0 from bpa_inventory_item where custom = 0", $user_id));
    }
}

add_action('wp_login', 'update_workers_number', 99, 2);
add_action('wp_login', 'update_sector', 99, 2);
add_action('wp_login', 'update_product', 99, 2);
add_action('wp_login', 'update_consumption', 99, 2);
add_action('wp_login', 'update_inventory', 99, 2);

?>